package com.ruanjian.api.controller;


import com.ruanjian.api.bean.ExperimentFund;
import com.ruanjian.api.bean.ExperimentStage;
import com.ruanjian.api.bean.Initial;
import com.ruanjian.api.bean.UserEarnings;
import com.ruanjian.api.service.IExperimentFundService;
import com.ruanjian.api.service.IExperimentStageService;
import com.ruanjian.api.service.IInitialService;
import com.ruanjian.api.service.IUserEarningsService;
import com.ruanjian.api.utils.AjaxResult;
import com.ruanjian.api.utils.DateUtil;
import com.ruanjian.api.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author shkstart
 * @create 2022-11-21 21:17
 */
@Api(tags = "父接口")
@Slf4j
@RestController
@RequestMapping("/api/java/experiment")
public class BaseController {

    @Autowired
    IExperimentFundService fundService;
    @Autowired
    IUserEarningsService userEarningsService;
    @Autowired
    IExperimentStageService stageService;
    @Autowired
    IInitialService initialService;
    @Autowired
    HttpServletRequest request;

    //存入user_earnings用户收益表
    /**
     * 每轮（1-12）资产（初始值1000）
     */
    int roundAssets = 1000;
    /**
     * 本轮收益（默认0）
     */
    int thisRoundIncome = 0;

    //存入experiment_fund基金表
    /**
     * 每只基金（1,2,3）用户投的比例（默认0）
     */
    double fundOneRatio = 0;
    double fundTwoRatio = 0;
    double fundThreeRatio = 0;
    /**
     * 每轮（1-12）用户投入每只基金（1,2,3）的实验点数
     */
    double inputPointOne = 0;
    double inputPointTwo = 0;
    double inputPointThree = 0;
    /**
     * 每只基金（1,2,3）每轮（1-12）实验点数变化（初始值100）
     */
    int fundOneValue = 100;
    int fundTwoValue = 100;
    int fundThreeValue = 100;

    //存入experiment_stage阶段表
    /**
     * 累计收益（默认0）
     */
    int addEarnings = 0;

    //待开发
    /**
     * 随机生成的增长概率
     */
    double fundOneGrowth = 0;
    double fundTwoGrowth = 0;
    double fundThreeGrowth = 0;
    /**
     * 增/减 率
     */
    double incry = 0.06;
    double decry = -0.05;
    /**
     * 每只基金（1,2,3）增/减情况（默认0）
     */
    double isFundOneIncry = 0;
    double isFundTwoIncry = 0;
    double isFundThreeIncry = 0;
    /**
     * 投出点数（默认0）
     */
    int throwPoints = 0;
    /**
     * 剩余点数（默认）
     */
    int remainingPoints = (int) (roundAssets - throwPoints);

    /**
     * 基础参数
     */
    Integer stageId = 0;
    Integer roundId = 0;
    long userId = 0;


    //前端传参：阶段数(Integer stageId) 轮数(Integer roundId) 基金一投资比例(double fundOne) 基金二投资比例(double fundTwo) 基金三投资比例(double fundThree)
    /**
     *   处理随机数
     *   处理用户操作
     * @param experimentId 实验场次
     * @param stageId 阶段id
     * @param roundId 轮数id
     * @param userId 用户id
     * @param fundOne 基金一比例
     * @param fundTwo 基金二比例
     * @param fundThree 基金三比例
     */
    @CrossOrigin
    @GetMapping("/handlerUser/{experimentId}/{stageId}/{roundId}/{userId}/{fundOne}/{fundTwo}/{fundThree}")
    public void handlerUser(@PathVariable("experimentId") Long experimentId,
                            @PathVariable("stageId") Integer stageId,
                            @PathVariable("roundId") Integer roundId,
                            @PathVariable("userId") Long userId,
                            @PathVariable("fundOne") double fundOne,
                            @PathVariable("fundTwo") double fundTwo,
                            @PathVariable("fundThree") double fundThree){
        //基本信息
        this.stageId = stageId;
        this.roundId = roundId;
        this.userId = userId;
        /**
         * 生成随机概率
         */
        fundOneGrowth = RandomUtil.PercentageRandom();
        fundTwoGrowth = RandomUtil.PercentageRandom();
        while (fundTwoGrowth == fundOneGrowth)
            fundTwoGrowth = RandomUtil.PercentageRandom();
        fundThreeGrowth = RandomUtil.PercentageRandom();
        while (fundThreeGrowth == fundOneGrowth || fundThreeGrowth == fundTwoGrowth)
            fundThreeGrowth = RandomUtil.PercentageRandom();
        /**
         * 每只基金（1,2,3）增/减情况
         */
        if(RandomUtil.isIncry(fundOneGrowth) == 0) isFundOneIncry = decry;
        else isFundOneIncry = incry;
        if(RandomUtil.isIncry(fundTwoGrowth) == 0) isFundTwoIncry = decry;
        else isFundTwoIncry = incry;
        if(RandomUtil.isIncry(fundThreeGrowth) == 0) isFundThreeIncry = decry;
        else isFundThreeIncry = incry;
        /**
         * 投资比例（前端传参）
         */
        fundOneRatio = fundOne;
        fundTwoRatio = fundTwo;
        fundThreeRatio = fundThree;
        /**
         * 投资每只基金（1,2,3）的实验点（公式：投资比例 * 每轮资产）
         */
        inputPointOne = fundOneRatio * roundAssets;
        inputPointTwo = fundTwoRatio * roundAssets;
        inputPointThree = fundThreeRatio * roundAssets;
        /**
         * 投出点数
         */
        throwPoints = (int) (roundAssets * (fundOneRatio + fundTwoRatio + fundThreeRatio));
        /**
         * 剩余点数
         */
        remainingPoints = (int) (roundAssets - throwPoints);
        /**
         * 本轮收益
         */
        thisRoundIncome = (int) ((inputPointOne * isFundOneIncry) + (inputPointTwo * isFundTwoIncry) + (inputPointThree * isFundThreeIncry));
        /**
         * 每轮（1-12）资产（投出 + 本轮收益 + 剩余）
         */
        roundAssets = throwPoints + thisRoundIncome + remainingPoints;
        /**
         * 累计收益（本轮收益 累加）
         */
        addEarnings = thisRoundIncome + addEarnings;
        /**
         * 每只基金（1,2,3）每轮（1-12）实验点数
         */
        fundOneValue = (int) (fundOneValue + (fundOneValue * isFundOneIncry));
        fundTwoValue = (int) (fundTwoValue + (fundTwoValue * isFundTwoIncry));
        fundThreeValue = (int) (fundThreeValue + (fundThreeValue * isFundThreeIncry));
//        System.out.println("=======================================阶段" + stageId + "=======================================");
//        System.out.println("++++++++++++++++++++++++++++++第" + roundId + "轮++++++++++++++++++++++++++++++");
//        System.out.println("(" + isFundOneIncry + ")" + "--" + "(" + isFundTwoIncry + ")" + "--" + "(" + isFundThreeIncry + ")");
//        System.out.println("```````````````````基金一```````````````````");
//        System.out.println("用户投入基金一的比例：" + fundOneRatio);
//        System.out.println("用户投入基金一的实验点：" + inputPointOne);
//        System.out.println("基金一变化情况：" + fundOneValue);
//        System.out.println("```````````````````基金二```````````````````");
//        System.out.println("用户投入基金二的比例：" + fundTwoRatio);
//        System.out.println("用户投入基金二的实验点：" + inputPointTwo);
//        System.out.println("基金二变化情况：" + fundTwoValue);
//        System.out.println("```````````````````基金三```````````````````");
//        System.out.println("用户投入基金三的比例：" + fundThreeRatio);
//        System.out.println("用户投入基金三的实验点：" + inputPointThree);
//        System.out.println("基金三变化情况：" + fundThreeValue);
//        System.out.println("```````````````````查看本轮您的个人资产组合收益情况```````````````````");
//        System.out.println("您当前的个人资产组合市值为（本轮资产）：" + roundAssets);
//        System.out.println("本轮收益：" + thisRoundIncome);
//        System.out.println("当前累计收益：" + addEarnings);
//        System.out.println("++++++++++++++++++++++++++++++end++++++++++++++++++++++++++++++");
//        System.out.println();
        /**
         * 存入experiment_fund基金表
         */
        ExperimentFund experimentFund1 = new ExperimentFund();
        experimentFund1.setFundId(1);
        experimentFund1.setStageId(stageId);
        experimentFund1.setRoundId(roundId);
        experimentFund1.setUserId(userId);
        experimentFund1.setFundRatio(fundOneRatio);
        experimentFund1.setFundValue(inputPointOne);
        experimentFund1.setFundPoint(fundOneValue);
        experimentFund1.setFundStorgeTime(DateUtil.getNowDate());
        fundService.insertSelective(experimentFund1);

        ExperimentFund experimentFund2 = new ExperimentFund();
        experimentFund2.setFundId(2);
        experimentFund2.setStageId(stageId);
        experimentFund2.setRoundId(roundId);
        experimentFund2.setUserId(userId);
        experimentFund2.setFundRatio(fundTwoRatio);
        experimentFund2.setFundValue(inputPointTwo);
        experimentFund2.setFundPoint(fundTwoValue);
        experimentFund2.setFundStorgeTime(DateUtil.getNowDate());
        fundService.insertSelective(experimentFund2);

        ExperimentFund experimentFund3 = new ExperimentFund();
        experimentFund3.setFundId(3);
        experimentFund3.setStageId(stageId);
        experimentFund3.setRoundId(roundId);
        experimentFund3.setUserId(userId);
        experimentFund3.setFundRatio(fundThreeRatio);
        experimentFund3.setFundValue(inputPointThree);
        experimentFund3.setFundPoint(fundThreeValue);
        experimentFund3.setFundStorgeTime(DateUtil.getNowDate());
        fundService.insertSelective(experimentFund3);

        /**
         * 存入user_earnings用户收益表
         */
        UserEarnings earnings = new UserEarnings();
        earnings.setStageId(stageId);
        earnings.setRoundId(roundId);
        earnings.setUserId(userId);
        earnings.setRoundEarnings(thisRoundIncome);
        earnings.setRoundAssets(roundAssets);
        earnings.setEarningsStorgeTime(DateUtil.getNowDate());
        earnings.setSumEarnings(addEarnings);
        userEarningsService.insertSelective(earnings);

        /**
         * 每十二轮重置（初始金额1000, 累计收益0, 基金(1,2,3)初始值100）
         */
        if(roundId == 12){
            /**
             * 将roundAssets和时间差 存入experiment_stage阶段表
             */
            ExperimentStage stage = new ExperimentStage();
            stage.setStageId(stageId);
            stage.setUserId(userId);
            stage.setStageTotalAssets(roundAssets);
//            时间
            stage.setStageStorgeTime(DateUtil.getNowDate());
            stageService.insertSelective(stage);
            //数据重置
            Initial initial = initialService.selectAllByExperimentId(experimentId);
            roundAssets = initial.getAssetInitial();
            addEarnings = 0;
            fundOneValue = initial.getFundoneInitial();
            fundTwoValue = initial.getFundtwoInitial();
            fundThreeValue = initial.getFundthreeInitial();
        }
    }

    @CrossOrigin
    @GetMapping("/test111")
    public AjaxResult test(){
        return AjaxResult.success().add("startTime",DateUtil.getNowDate());
    }

    /**
     * 设置基金初始值
     * @param experimentId
     */
    @CrossOrigin
    @GetMapping("/setInitial/{experimentId}")
    public void setInitial(@PathVariable("experimentId") Long experimentId){
        Initial initial = initialService.selectAllByExperimentId(experimentId);
        roundAssets = initial.getAssetInitial();
        fundOneValue = initial.getFundoneInitial();
        fundTwoValue = initial.getFundtwoInitial();
        fundThreeValue = initial.getFundthreeInitial();
    }

    @CrossOrigin
    @GetMapping("/clear/{experimentId}")
    public void clear(@PathVariable("experimentId") Long experimentId){
        Initial initial = initialService.selectAllByExperimentId(experimentId);

//        ExperimentStage stage = new ExperimentStage();
//        stage.setStageId(stageId);
//        stage.setUserId(userId);
//        stage.setStageTotalAssets(roundAssets);
//        //时间设置
//        stage.setStageStorgeTime(DateUtil.getNowDate());
//        stageService.insertSelective(stage);
        System.out.println(stageId);
        System.out.println(userId);
        System.out.println(roundAssets);

        //数据重置
        roundAssets = initial.getAssetInitial();
        addEarnings = 0;
        fundOneValue = initial.getFundoneInitial();
        fundTwoValue = initial.getFundtwoInitial();
        fundThreeValue = initial.getFundthreeInitial();
    }


}
